package com.lyc.tokendemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyc.tokendemo.domain.LoginUser;
import com.lyc.tokendemo.domain.User;
import com.lyc.tokendemo.mapper.MenuMapper;
import com.lyc.tokendemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果数据库中没有该用户
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }

//        List<String> permissions = new ArrayList<>(Arrays.asList("test", "admin"));
        List<String> perms = menuMapper.getPermsByUserId(user.getId());
        // 返回用户信息
        // 把数据封装成UserDetails
        return new LoginUser(user, perms);
    }
}
